package com.atguigu.reggie.globalException;

import com.atguigu.reggie.common.R;
import com.atguigu.reggie.selfException.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-10-10 15:30
 */

/**
 * 全局异常处理
 */
                              // 1、拦截加了RestController,Controller的注解
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 数据添加重复异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlExceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String[] msg = ex.getMessage().split(" ");
            return R.error(msg[2]+"已存在");
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException ex){

        log.info(ex.getMessage());

        // 直接返回异常信息
        return R.error(ex.getMessage());
    }

}
